#pragma once
#include <iostream>
#include <string>
#include <sys/ipc.h> // inter-process-comm
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

const std::string pathname = "/home/lcx/linux_code/ProcessComm/SharedMemory";
const int proj_id = 0x11223344;
const std::string filename = "fifo";
// 共享内存的大小，强烈建议设置为n*4096
const int size = 4097; // 底层会开2*4096，但是给到用户后，只能使用4097

key_t GetKey()
{
    key_t key = ftok(pathname.c_str(), proj_id);
    if (key < 0)
    {
        std::cerr << "errno" << errno << ", errstring: " << strerror(errno) << std::endl;
        return 1;
    }
    return key;
}

std::string ToHex(int n)
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "0x%x", n);
    return buffer;
}

int CreatShmHelper(key_t key, int flag)
{
    int shmid = shmget(key, size, flag); // 不存在创建，存在返回错误(保证创建的是全新的)
    if (shmid < 0)
    {
        std::cerr << "errno" << errno << ", errstring: " << strerror(errno) << std::endl;
        exit(2);
    }
    return shmid;
}

int CreatShm(key_t key)
{
    return CreatShmHelper(key, IPC_CREAT | IPC_EXCL | 0644);
}

int GetShm(key_t key)
{
    return CreatShmHelper(key, IPC_CREAT/*0也可以*/);   
}

bool MakeFifo()
{
    int n = mkfifo(filename.c_str(), 0666);
    if(n < 0)
    {
        std::cerr << "errno" << errno << ", errstring: " << strerror(errno) << std::endl;
        return false;
    }

    std::cout << "mkfifo success... read" << std::endl;
    return true;
}
